import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import pool from '@/lib/db';

export async function POST(req) {
  const session = await getServerSession(authOptions);
  if (!session?.user?.email) {
    return Response.json({ error: '未登录' }, { status: 401 });
  }
  const { newEmail } = await req.json();
  if (!newEmail) {
    return Response.json({ error: '参数不完整' }, { status: 400 });
  }
  // 邮箱格式校验
  const emailRegex = /^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/;
  if (!emailRegex.test(newEmail)) {
    return Response.json({ error: '邮箱格式不正确' }, { status: 400 });
  }
  // 检查邮箱唯一性
  const { rows: existRows } = await pool.query('SELECT id FROM users WHERE email = $1', [newEmail]);
  if (existRows.length > 0) {
    return Response.json({ error: '该邮箱已被注册' }, { status: 400 });
  }
  await pool.query('UPDATE users SET email = $1 WHERE email = $2', [newEmail, session.user.email]);
  return Response.json({ success: true });
} 